const axios = require('./utils/axios');

App({
  onLaunch() {
    this.login();
  },
  globalData: {
    user: null,
    header: null,

    loginPromise: null,
    tabbars: [
      {
        "pagePath": "/pages/index/index",
        "text": "首页",
        "iconPath": "/imgs/首页-灰.svg",
        "selectedIconPath": "/imgs/首页.svg",
        "value": 0
      }, {
        "pagePath": "/pages/jobs/jobs",
        "text": "岗位",
        "iconPath": "/imgs/发现-灰.svg",
        "selectedIconPath": "/imgs/发现.svg",
        "value": 1
      }, {
        "pagePath": "/pages/user/user",
        "text": "个人",
        "iconPath": "/imgs/我的-灰.svg",
        "selectedIconPath": "/imgs/我的.svg",
        "value": 3
      },
    ],
    tabbarListeners: []
  },

  login(callback) {
    if(this.globalData.loginPromise) {
      return this.globalData.loginPromise.then(res => {
        if(callback && typeof callback == 'function') {
          return callback();
        } else {
          return res;
        }
      });
    }

    this.globalData.loginPromise = new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if(!res.code) {
            return reject(res);
          }
          axios.get('/user', { code: res.code }).then(res => {
            console.log(res);
            const { code, data, err } = res;
            if(code != 200) {
              resolve(err);
            } else {
              this.globalData.user = data;
              this.globalData.header = {
                Authorization: data.token
              };
              if(data.cName) {
                this.changeCompanyMode();
              }
              if(callback && typeof callback == 'function') {
                resolve(callback);
              } else {
                resolve(data);
              }
            }
          }).catch(err => {
            reject(err);
          });
        }, fail: err => {
          return reject(err);
        }
      })
    });
  },

  changeTabbars(list) {
    console.log(list);
    this.globalData.tabbars = list;
    this.globalData.tabbarListeners.forEach(item => {
      item(list);
    });
  },

  changeCompanyMode() {
    const list = [
      {
        "pagePath": "/pages/index/index",
        "text": "首页",
        "iconPath": "/imgs/首页-灰.svg",
        "selectedIconPath": "/imgs/首页.svg",
        "value": 0
      }, {
        "pagePath": "/pages/jobs/jobs",
        "text": "岗位",
        "iconPath": "/imgs/发现-灰.svg",
        "selectedIconPath": "/imgs/发现.svg",
        "value": 1
      }, {
        "pagePath": "/pages/staffs/staffs",
        "text": "求职",
        "iconPath": "/imgs/发现-灰.svg",
        "selectedIconPath": "/imgs/发现.svg",
        "value": 2
      }, {
        "pagePath": "/pages/user/user",
        "text": "个人",
        "iconPath": "/imgs/我的-灰.svg",
        "selectedIconPath": "/imgs/我的.svg",
        "value": 3
      },
    ];
    this.changeTabbars(list);
  }
});
